package adapteurMediaStore;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Log;

import com.insta.playdroid.SongsActivity2;
import com.insta.playdroid.metier.domain.Song;

public class AdapteurSongMediaStore implements IAdapteurMediaStore<Song> {

	private Context context;

	public AdapteurSongMediaStore(Context context) {
		this.context = context;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see adapteurMediaStore.IAdapteurMediaStore#collectAllValuesFromDB()
	 */
	@Override
	public List<Song> collectAllValuesFromDB() {

		List<Song> songs = new ArrayList<Song>();
		int id;
		String titre;
		String album;
		String artist;
		String location;

		// the cursor we will use to iterate over the db results
		Cursor cursor = null;

		// the list of columns our search relates to
		final String[] projection = new String[] {
				MediaStore.Audio.AudioColumns._ID,
				MediaStore.Audio.AudioColumns.TITLE,
				MediaStore.Audio.AudioColumns.ARTIST,
				MediaStore.Audio.AudioColumns.ALBUM,
				MediaStore.Audio.AudioColumns.DATA,
		/* MediaStore.Audio.AudioColumns.ALBUM_ART */};

		// how we want to sort our results
		final String sortOrder = MediaStore.Audio.AudioColumns.TITLE
				+ " COLLATE LOCALIZED ASC";

		try {
			// the uri of the table that we want to query
			Uri uri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;

			// launch the query
			cursor = context.getContentResolver().query(uri, projection, null,
					null, sortOrder);

			if (cursor != null) {
				songs = new ArrayList<Song>(cursor.getCount());

				cursor.moveToFirst();
				while (!cursor.isAfterLast()) {
					// get the 1st parameter in our query string
					// (AlbumColumns.ALBUM)

					id = cursor.getInt(0);
					titre = cursor.getString(1);
					artist = cursor.getString(2);
					album = cursor.getString(3);
					location = cursor.getString(4);
					// albumArt = "";// cursor.getString(5);
					songs.add(new Song(id, titre, location, artist, album, null));

					cursor.moveToNext();

				}
			}
		} catch (Exception ex) {
			Log.e(SongsActivity2.class.getName(),
					"Error querying music db for all albums");
		} finally {
			if (cursor != null) {
				cursor.close();
			}

		}

		return songs;

	}
}
